<template>
  <div class="customer-list">
    <span style="font-size: 30px; position: relative; top: -10px"
      >仓库盘点</span
    >

    <div class="add-button-bottom-right">
      <el-button
        type="primary"
        icon="el-icon-loading"
        class="audit-button"
        @click="handleAudit"
        >审核</el-button
      >

      <el-button class="add-button" @click="AddCount">新增仓库盘点</el-button>
    </div>

    <div style="display: flex; align-items: center">
      <el-input
        style="width: 300px; margin: 10px 20px 10px 0"
        v-model="searchKeyword"
        @change="getInvWarehouse"
        placeholder="请输入出库物品名称"
        clearable
      ></el-input>
      <el-button
        icon="el-icon-search"
        circle
        @change="getInvWarehouse"
      ></el-button>
      <!-- 日期选择器 -->
      <el-date-picker
        placeholder="选择日期"
        v-model="selectedDate"
        @change="getInvWarehouse"
      ></el-date-picker>
    </div>

    <el-table
      :data="iwiData"
      border
      stripe
      style="width: 100%"
      class="centered-table"
      @selection-change="handleSelectionChange2"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="iwi_code" label="盘点单号"></el-table-column>
      <el-table-column prop="iwi_W_Name" label="盘点仓库"></el-table-column>

      <el-table-column prop="iwi_date" label="盘点日期" width="auto">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.iwi_date) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="iwi_checker" label="盘点人"></el-table-column>

      <el-table-column prop="iwi_AuditStatus" label="审核状态" width="auto">
        <template slot-scope="scope">
          <span
            :style="{
              color: scope.row.iwi_AuditStatus == true ? '#2ab600' : 'red',
            }"
          >
            {{ scope.row.iwi_AuditStatus == true ? "已审核" : "未审核" }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-view"
            @click="handleSee(scope.row)"
            >盘点详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-divider></el-divider>
    <!-- 下划线分隔 -->
    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="change2"
      @current-change="Ymchange2"
      :current-page="currentPage2"
      :page-sizes="[10, 15, 20, 50]"
      :page-size="pageSize2"
      layout="total, sizes, prev, pager, next, jumper"
      :total="rows"
    >
    </el-pagination>

    <el-dialog
      title="新增仓库盘点仓库"
      :visible.sync="isAddCount"
      width="1100px"
      style="height: 800px"
      :close-on-click-modal="false"
      class="qw"
      :before-close="handleClose"
    >
      <div class="custom-div1">
        <el-button @click="confirmInventory">确认盘点</el-button>
      </div>
      <el-button
        class="orange-button"
        style="position: absolute; top: 43px; left: 10; padding: 10px"
        @click="returnToList2"
        >返回列表</el-button
      >
      <el-form label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="盘点单号">
              <el-input
                v-model="AddInv.iwi_code"
                style="width: 200px"
                disabled
                placeholder="系统自动获取"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="盘点仓库">
              <el-select
                v-model="AddInv.iwi_W_Name"
                placeholder="请选择盘点仓库"
                style="width: 200px"
              >
                <el-option
                  v-for="item in Wareh"
                  :key="item.w_Name"
                  :label="item.iwi_W_Name"
                  :value="item.w_Name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="盘点日期">
              <el-date-picker style="width: 200px" v-model="AddInv.iwi_date">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点人">
              <el-select
                v-model="AddInv.iwi_checker"
                auto-complete="off"
                placeholder="请选择盘点人"
                style="width: 200px"
              >
                <el-option
                  v-for="employee in employees"
                  :key="employee.employee_id"
                  style="width: 100%"
                  :label="employee.employee_name"
                  :value="employee.employee_name"
                  class="kuang"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-form-item
            label="外键Id"
            style="position: relative; margin-left: -180px; top: 10px"
            v-if="Ycchange"
          >
            <el-input
              v-model="AddInv.inv_WarehouseInveniwi_id"
              v-if="Ycchange"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <h3>仓库盘点材料明细</h3>

      <div class="button-container">
        <el-button @click="AddInvPD" class="custom-button">添加</el-button>
      </div>
      <div class="product-list-container">
        <el-table
          :data="iwiDataC"
          border
          stripe
          style="width: 100%"
          class="dataTable"
        >
          <el-table-column
            prop="iwi_id_C"
            label="序号"
            type="index"
          ></el-table-column>

          <el-table-column prop="igi_name" label="物品名称" width="auto">
          </el-table-column>

          <el-table-column
            prop="igi_code"
            label="规格型号"
            width="auto"
          ></el-table-column>

          <el-table-column
            prop="igi_unit"
            label="单位"
            width="auto"
          ></el-table-column>

          <el-table-column
            prop="igi_quantity"
            label="账面数量"
            width="auto"
          ></el-table-column>

          <el-table-column label="盘点数量">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.igi_PDNumber"
                placeholder="请输入"
                @input="onCheckQuantityInput(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="breakState" label="盈亏状态" width="auto">
            <template slot-scope="scope">
              <span
                v-if="
                  scope.row.breakState !== null && scope.row.breakState !== ''
                "
                :style="{
                  color:
                    scope.row.breakState == 1
                      ? '#FFA07A'
                      : scope.row.breakState == 2
                      ? 'red'
                      : '#87CEEB',
                }"
              >
                {{
                  scope.row.breakState == 0
                    ? ""
                    : scope.row.breakState == 1
                    ? "盘盈"
                    : scope.row.breakState == 2
                    ? "盘亏"
                    : "无盈亏"
                }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="breakQuantity" label="盈亏数量" width="75px">
            <template slot-scope="scope">
              <span
                :style="{
                  color:
                    scope.row.breakState === 1
                      ? 'green'
                      : scope.row.breakState === 2
                      ? 'red'
                      : 'black',
                }"
              >
                {{ scope.row.breakQuantity }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="changeModel"
            @current-change="YmchangeModel"
            :current-page="currentPage3"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize3"
            layout="total, sizes, prev, pager, next, jumper"
            :total="modelfroms"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>

    <!-- 选择从表材料 -->
    <el-dialog title="添加材料" :visible.sync="dialogVisible" width="45%">
      <div>
        <el-card class="box-card1">
          <div>
            <!-- 头部 尾 -->
            <el-table
              :data="Cdate"
              ref="MyDate"
              border
              height="250"
              @select="handleSelectionChange3"
              style="width: 100%"
            >
              <el-table-column fixed type="selection" width="55" />
              <el-table-column fixed width="50" label="序号" prop="igi_id" />
              <el-table-column fixed prop="igi_name" label="物品名称" />
              <el-table-column fixed prop="igi_code" label="规格型号" />
              <el-table-column fixed prop="igi_unit" label="单位" />
              <el-table-column fixed prop="igi_quantity" label="数量" />
            </el-table>
          </div>
        </el-card>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="hpxxhq">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 盘点详情模态框 -->
    <el-dialog
      title=""
      :visible.sync="IshandleSee"
      width="50%"
      :before-close="handleClose"
    >
      <h3>仓库盘点信息</h3>
      <el-button
        class="orange-button"
        style="position: absolute; top: 13px; left: 10; padding: 10px"
        @click="returnToList"
        >返回列表</el-button
      >
      <el-form :model="UpdateInv" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="盘点单号">
              <el-input
                v-model="UpdateInv.iwi_code"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点仓库">
              <el-input
                v-model="UpdateInv.iwi_W_Name"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点日期">
              <el-date-picker
                style="width: 200px"
                v-model="UpdateInv.iwi_date"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点人">
              <el-select
                v-model="UpdateInv.iwi_checker"
                auto-complete="off"
                placeholder="请选择盘点人"
                style="width: 200px"
                disabled
              >
                <el-option
                  v-for="employee in employees"
                  :key="employee.employee_id"
                  style="width: 100%"
                  :label="employee.employee_name"
                  :value="employee.employee_name"
                  class="kuang"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="审核人">
              <el-input
                v-model="UpdateInv.iwi_auditor"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间">
              <el-input
                v-model="UpdateInv.iwi_auditTime"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="审核状态">
              <el-input v-model="displayText2" style="width: 200px" disabled />
            </el-form-item>
          </el-col>

          <el-form-item
            label="外键Id"
            style="position: relative; margin-left: -180px; top: 10px"
            v-if="Ycchange"
          >
            <el-input
              v-model="UpdateInv.inv_WarehouseInveniwi_id"
              v-if="Ycchange"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <h3>仓库盘点材料明细</h3>

      <div class="product-list-container">
        <el-table
          :data="iwiDataC"
          border
          stripe
          style="width: 100%"
          class="dataTable"
        >
          <el-table-column
            prop="iwi_id_C"
            label="序号"
            type="index"
          ></el-table-column>

          <el-table-column
            prop="igi_name"
            label="物品名称"
            width="120px"
          ></el-table-column>

          <el-table-column
            prop="igi_code"
            label="规格型号"
            width="120px"
          ></el-table-column>

          <el-table-column
            prop="igi_unit"
            label="单位"
            width="50px"
          ></el-table-column>

          <el-table-column
            prop="igi_warehouse"
            label="盘点仓库"
            width="auto"
          ></el-table-column>

          <el-table-column
            prop="igi_quantity"
            label="账面数量"
            width="80px"
          ></el-table-column>

          <el-table-column
            prop="igi_PDNumber"
            label="盘点数量"
            width="80px"
          ></el-table-column>

          <el-table-column prop="breakState" label="盈亏状态" width="auto">
            <template slot-scope="scope">
              <span
                v-if="
                  scope.row.breakState !== null && scope.row.breakState !== ''
                "
                :style="{
                  color:
                    scope.row.breakState == 1
                      ? '#FFA07A'
                      : scope.row.breakState == 2
                      ? 'red'
                      : '#87CEEB',
                }"
              >
                {{
                  scope.row.breakState == 0
                    ? ""
                    : scope.row.breakState == 1
                    ? "盘盈"
                    : scope.row.breakState == 2
                    ? "盘亏"
                    : "无盈亏"
                }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="breakQuantity" label="盈亏数量" width="75px">
            <template slot-scope="scope">
              <span
                :style="{
                  color:
                    scope.row.breakState === 1
                      ? 'green'
                      : scope.row.breakState === 2
                      ? 'red'
                      : 'black',
                }"
              >
                {{ scope.row.breakQuantity }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="changeMode9"
            @current-change="YmchangeMode9"
            :current-page="currentPage9"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize9"
            layout="total, sizes, prev, pager, next, jumper"
            :total="modelfromss"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import $http from "@/routers/base";
import moment from "moment";
export default {
  data() {
    return {
      index: 0,
      isAddCount: false,
      customers: [], // 客户列表数据
      WarehouseData: [],
      iwiData: [],
      iwiDataC: [],
      currentPage1: 1, //当前页
      pageSize: 6, //每页显示数
      rows1: 0, //总行数

      currentPage2: 1,
      pageSize2: 10,
      rows: 0,

      currentPage3: 1,
      pageSize3: 3,
      modelfroms: 0,

      currentPage9: 1,
      pageSize9: 3,
      modelfromss: 0,

      selectedRows: [], // 存储当前选中的行
      selectedRows2: [],
      selectedRows3: [],
      searchKeyword: "",
      dateString: "",
      selectedDate: "",

      IshandleInv: false, //仓库盘点模态框
      Ycchange: false,
      AddInv: {
        iwi_id: "",
        iwi_code: "",
        iwi_W_Name: "",
        iwi_date: "",
        iwi_checker: "",
        iwi_auditor: "",
        iwi_auditTime: "",
        iwi_AuditStatus: "",
      },
      UpdateInv: {
        iwi_id: "",
        iwi_code: "",
        iwi_W_Name: "",
        iwi_date: "",
        iwi_checker: "",
        iwi_auditor: "",
        iwi_auditTime: "",
        iwi_AuditStatus: "",
      },
      employees: [],
      selectedModelId: 0,
      inv_WarehouseInveniwi_id: 0,

      currentSequence: 1,

      products: [], //查询物品库存
      breakState: null, // 当前的盈亏状态，null 表示尚未计算

      Wareh: [],
      IshandleSee: false,
      dialogVisible: false,
      Cdate: [],
      selectedProducts: [], // 存储用户选择的物品
    };
  },
  computed: {
    displayText2() {
      return this.AddInv.iwi_AuditStatus ? "已审核" : "未审核";
    },
  },
  mounted() {
    this.getInvWarehouse();
    this.loadEmployee();
    this.fetchUpaheModeFrom2();
    this.WarehAit();
  },
  methods: {
    //根据仓库查询物品名称
    loadGoodsInv() {
      const igi_warehouse = this.AddInv.iwi_W_Name;
      $http
        .get(
          `InvWarehouseInventory/QueryProducts?igi_warehouse=${igi_warehouse}`
        )
        .then((response) => {
          this.Cdate = response;
          this.Cdate.forEach((product) => {
            console.log(product.di_name);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    AddInvPD() {
      this.dialogVisible = true;
      this.loadGoodsInv(); // 加载物品名称
    },
    hpxxhq() {
      if (this.selectedProducts.length > 0) {
        this.selectedProducts.forEach((product) => {
          if (!Array.isArray(this.iwiDataC)) {
            this.iwiDataC = [];
          }
          this.iwiDataC.push({
            iwi_id_C: this.currentSequence++,
            ...product,
          });
        });
        this.selectedProducts = [];
        this.dialogVisible = false;
      }
    },
    handleSelectionChange3(selection) {
      this.selectedProducts = selection;
    },
    confirmInventory() {
      let isFormEmpty = true;
      if (
        !this.AddInv.iwi_W_Name &&
        !this.AddInv.iwi_date &&
        !this.AddInv.iwi_checker
      ) {
        this.$message.error("盘点数据不能为空，请填写完整表单");
        isFormEmpty = false;
      } else {
        let errorMessage = "";
        if (!this.AddInv.iwi_W_Name) {
          errorMessage = "盘点仓库不能为空";
        }
        if (!this.AddInv.iwi_checker) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "盘点人不能为空";
        }
        if (!this.AddInv.iwi_date) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "盘点日期不能为空";
        }
        if (errorMessage) {
          this.$message.error(errorMessage);
          return;
        }
      }

      if (!isFormEmpty) {
        return;
      }

      this.mainData = {
        iwi_id: 0,
        iwi_code: this.AddInv.iwi_code,
        iwi_W_Name: this.AddInv.iwi_W_Name,
        iwi_date: this.AddInv.iwi_date,
        iwi_checker: this.AddInv.iwi_checker,
        iwi_auditor: null,
        iwi_auditTime: null,
        iwi_AuditStatus: false,
        isDeleted: false,
        inv_WarehouseInven_C: this.iwiDataC,
      };
      $http
        .post("InvWarehouseInventory/AddReturn", this.mainData)
        .then((response) => {
          if (response) {
            this.$message.success("添加成功！");
            this.getInvWarehouse();
            this.isAddCount = false;
            // 清空文本框字段
            this.AddInv.iwi_W_Name;
            this.AddInv.iwi_date = "";
            this.AddInv.iwi_checker = "";
            this.iwiDataC = [];
          } else {
            this.$message.error("添加失败！请重新添加！");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
    },
    //仓库
    WarehAit() {
      $http
        .get("Warehouse/IQuery")
        .then((res) => {
          // 根据type属性过滤出单位数据
          this.Wareh = res;
          this.Wareh.forEach((unit) => {
            console.log(unit.dd_label);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    //根据物品名称查询规格型号、单位和账面数量
    handleProductChange(row, igi_name) {
      const WarehouseData = this.products.find(
        (item) => item.igi_name === igi_name
      );

      if (WarehouseData) {
        row.igi_code = WarehouseData.igi_code; // 更新规格型号
        row.igi_unit = WarehouseData.igi_unit; // 更新单位
        row.igi_quantity = WarehouseData.igi_quantity; // 更新账面数量
      }
    },

    // 加载盘点人数据
    loadEmployee() {
      $http
        .get("Employee/Query")
        .then((response) => {
          if (response) {
            this.employees = response;
          } else {
            console.error("Invalid response format:", response);
          }
        })
        .catch((error) => {
          console.error("Error fetching contacts:", error);
        });
    },
    handleClose(done) {
      done();
    },
    change1: function (size) {
      this.pageSize = size;
      this.currentPage1 = 1;
      this.getWarehouse();
    },
    Ymchange1: function (page) {
      this.currentPage1 = page;
      this.getWarehouse();
    },
    //日期转型
    formatDate(dateString) {
      if (!dateString) {
        return "";
      }
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return "";
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    //仓库盘点查询
    getInvWarehouse() {
      this.dateString = moment(this.selectedDate).format("YYYY-MM-DD");
      this.where = `1=1`;
      if (this.searchKeyword) {
        this.where += `AND (iwi_W_Name LIKE '%${this.searchKeyword}%' OR iwi_checker LIKE '%${this.searchKeyword}%' or iwi_code like '%${this.searchKeyword}%')`;
      }
      if (this.selectedDate) {
        this.where += `AND (CAST(iwi_date AS DATE) ='${this.dateString}')`;
      }

      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("InvWarehouseInventory/GetFenYe", {
          params: {
            currentPage: this.currentPage2,
            pageSize: this.pageSize2,
            where: this.where,
          },
        })
        .then((res) => {
          this.iwiData = res.iwiData;
          this.rows = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    change2: function (size) {
      this.pageSize = size;
      this.currentPage2 = 1;
      this.getInvWarehouse();
    },
    Ymchange2: function (page) {
      this.currentPage2 = page;
      this.getInvWarehouse();
    },

    fetchUpaheModeFrom2() {
      this.where = "inv_WarehouseInveniwi_id=" + this.selectedModelId;
      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("InvWarehouseInventory/GetFenYeC", {
          params: {
            currentPage: this.currentPage3,
            pageSize: this.pageSize3,
            where: this.where,
          },
        })
        .then((res) => {
          this.iwiDataC = res.iwiDataC;
          this.modelfroms = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    changeModel: function (size) {
      this.pageSize3 = size;
      this.currentPage3 = 1;
      this.fetchUpaheModeFrom2();
    },
    YmchangeModel: function (page) {
      this.currentPage3 = page;
      this.fetchUpaheModeFrom2();
    },

    fetchUpaheModeFrom() {
      this.where = "inv_WarehouseInveniwi_id=" + this.selectedModelId;
      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("InvWarehouseInventory/GetFenYeC", {
          params: {
            currentPage: this.currentPage9,
            pageSize: this.pageSize9,
            where: this.where,
          },
        })
        .then((res) => {
          this.iwiDataC = res.iwiDataC;
          this.modelfromss = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    changeMode9: function (size) {
      this.pageSize9 = size;
      this.currentPage9 = 1;
      this.fetchUpaheModeFrom();
    },
    YmchangeMode9: function (page) {
      this.currentPage9 = page;
      this.fetchUpaheModeFrom();
    },

    //选中行
    handleSelectionChange(selection) {
      this.selectedRows = selection; // 更新选中的行
    },
    handleSelectionChange2(selection) {
      this.selectedRows2 = selection; // 更新选中的行
    },

    //新增仓库盘点
    AddCount() {
      this.isAddCount = true;
    },
    Add() {
      const selectedRows = this.$refs.tableName.selection;
      //检查是否至少选择了一行
      if (selectedRows.length > 0) {
        // 遍历选中的每一行数据
        selectedRows.forEach((row) => {
          const postData = {
            iwi_code: "",
            iwi_W_Name: row.igi_warehouse,
            iwi_date: this.formatDate(new Date()), // 盘点日期，这里使用当前日期
            iwi_checker: "",
            iwi_auditor: "",
            iwi_auditTime: null,
            iwi_AuditStatus: false,

            inv_WarehouseInven_C: Array.isArray(this.iwiDataC)
              ? this.iwiDataC.map(() => ({
                  isDeleted: false,
                  igi_name: "",
                  igi_code: "",
                  igi_unit: "",
                  igi_quantity: 0,
                  igi_PDNumber: "",
                  igi_warehouse: "",
                  breakState: 0,
                  breakQuantity: 0,
                  inv_WarehouseInveniwi_id: this.AddInv.iwi_id,
                }))
              : [],
          };
          $http
            .post("InvWarehouseInventory/AddReturn", postData)
            .then((res) => {
              if (res) {
                //this.$message({
                // message: "添加成功！",
                // type: "success",
                //});
                this.isAddCount = false;
                this.getInvWarehouse();
                this.getWarehouse();
              } else {
                this.$message({
                  message: "添加失败！",
                  type: "error",
                });
              }
            })
            .catch((error) => {
              console.error("添加失败:", error);
              this.$message.error("添加失败，请稍后重试！");
            });
        });
      } else {
        this.$message.warning("请至少选择一行数据！");
      }
    },
    handleSee(row) {
      this.IshandleSee = true;
      this.selectedModelId = row.iwi_id;
      this.UpdateInv.inv_WarehouseInveniwi_id = this.selectedModelId;

      this.fetchUpaheModeFrom();
      this.$set(this.UpdateInv, "iwi_id", row.iwi_id);
      this.$set(this.UpdateInv, "iwi_code", row.iwi_code);
      this.$set(this.UpdateInv, "iwi_W_Name", row.iwi_W_Name);
      this.$set(this.UpdateInv, "iwi_date", row.iwi_date);
      this.$set(this.UpdateInv, "iwi_checker", row.iwi_checker);
      this.$set(this.UpdateInv, "iwi_auditor", row.iwi_auditor);
      this.$set(this.UpdateInv, "iwi_auditTime", row.iwi_auditTime);
      this.$set(this.UpdateInv, "iwi_AuditStatus", row.iwi_AuditStatus);
    },

    PanD() {
      const updateData = {
        iwi_id: this.AddInv.iwi_id,
        iwi_code: this.AddInv.iwi_code,
        iwi_W_Name: this.AddInv.iwi_W_Name,
        iwi_date: this.AddInv.iwi_date,
        iwi_checker: this.AddInv.iwi_checker,
        iwi_auditor: this.AddInv.iwi_auditor,
        iwi_auditTime: this.AddInv.iwi_auditTime,
        iwi_AuditStatus: false,
        inv_WarehouseInven_C: this.iwiDataC.map((item) => ({
          iwi_id_C: item.iwi_id_C,
          igi_name: item.igi_name,
          igi_code: item.igi_code,
          igi_unit: item.igi_unit,
          igi_quantity: item.igi_quantity,
          igi_PDNumber: item.igi_PDNumber,
          igi_warehouse: item.igi_warehouse,
          isDeleted: item.isDeleted,
          inv_WarehouseInveniwi_id: this.AddInv.iwi_id,
        })),
      };
      // 检查审核状态，如果为 true，则不允许修改
      if (this.AddInv.iwi_AuditStatus === true) {
        this.$message.error("修改失败：该盘点订单已审核，不能进行修改！");
        return;
      }
      $http
        .put("InvWarehouseInventory/UpdateInv", updateData)
        .then((response) => {
          if (response) {
            this.$message.success("修改成功！");
            this.getInvWarehouse();
            this.isAddCount = false;
          } else {
            this.$message.error("修改失败！请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("修改失败：" + error.message);
        });
    },
    Delete(index) {
      // 首先确保下标在合法范围内
      if (index >= 0 && index < this.iwiDataC.length) {
        // 从数组中删除指定下标的元素
        this.iwiDataC.splice(index, 1);
        // 深拷贝 allData 的值给 testArr
        this.testArr = JSON.parse(JSON.stringify(this.iwiDataC));
        // 提示用户删除成功
        this.$message.success("删除成功！");
      } else {
        // 如果下标不在合法范围内，给出相应的提示
        this.$message.error("无法删除，下标越界！");
      }
    },

    confirmUpdate(row) {
      if (row.iwi_id_C) {
        this.updateSubIwiDataC(row);
      } else {
        row.inv_WarehouseInveniwi_id = this.AddInv.iwi_id;
        this.addSubIwiDataC(row);
      }
    },
    updateSubIwiDataC(data) {
      $http
        .put("InvWarehouseInventory/Update_C", data)
        .then((response) => {
          if (response) {
            // this.$message.success("修改成功！");
          } else {
            this.$message.error("修改失败，请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("修改失败：" + error.message);
        });
    },

    addSubIwiDataC(data) {
      $http
        .post("InvWarehouseInventory/Add_C", data)
        .then((response) => {
          if (response) {
            //this.$message.success("添加成功！");
          } else {
            this.$message.error("添加失败，请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
    },

    // 根据账面数量和盘点数量计算盈亏状态和盈亏数量
    calculateBreakState(inventoryRecord) {
      const inventoryQuantity = parseInt(inventoryRecord.igi_quantity, 10);
      const checkQuantity = parseInt(inventoryRecord.igi_PDNumber, 10);

      if (isNaN(inventoryQuantity) || isNaN(checkQuantity)) {
        inventoryRecord.breakState = null;
        inventoryRecord.breakQuantity = null;
        return null;
      }

      let breakState;
      let breakQuantity = checkQuantity - inventoryQuantity;

      if (breakQuantity > 0) {
        breakState = 1; // 盘盈
      } else if (breakQuantity < 0) {
        breakState = 2; // 盘亏
      } else {
        breakState = 3; // 无盈亏
        breakQuantity = "0";
      }

      inventoryRecord.breakState = breakState;
      inventoryRecord.breakQuantity = breakQuantity;

      return breakState;
    },

    onCheckQuantityInput(row) {
      this.calculateBreakState(row);
    },

    //盘点审核
    handleAudit() {
      if (this.selectedRows2.length === 0) {
        this.$message.warning("请至少选择一个销售订单进行审核");
        return;
      }
      const auditedRows = this.selectedRows2.filter(
        (row) => row.iwi_AuditStatus === true
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的销售订单中已有部分订单已经审核通过，不能再次审核"
        );
        return;
      }
      this.$confirm("此操作将审核选中的销售订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows2.forEach((row) => {
            this.auditSaleOrder(row.iwi_id);
          });
          this.selectedRows2 = [];
          this.getInvWarehouse();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消审核",
          });
        });
    },
    //审核方法
    auditSaleOrder(iwi_id) {
      $http
        .post(`InvWarehouseInventory/AuditWarehouseInven/${iwi_id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.getInvWarehouse();
        })
        .catch((error) => {
          this.$message.error("审核失败，请稍后再试");
          console.error("Audit error:", error);
        });
    },
    //返回列表
    returnToList() {
      this.iwiDataC = [];
      this.IshandleSee = false;
    },
    returnToList2() {
      this.isAddCount = false;
      this.AddInv.iwi_W_Name = "";
      this.AddInv.iwi_date = "";
      this.AddInv.iwi_checker = "";
      this.iwiDataC = [];
    },
  },
};
</script>

<style>
.button-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /* 垂直居中 */
  height: 100%;
  /* 确保按钮容器占据整个高度 */
  padding-top: 10px;
  float: left;
}
.custom-button {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  background-color: #1abc9c;
  width: 60px;
  height: 30px;
  color: #fff;
  font-size: 12px;
  border: none;
}
.custom-div2 button {
  background-color: #4fc1b0; /* 设置背景颜色为绿色 */
  border: none;
  color: white; /* 设置字体颜色为白色 */
  padding: 10px 20px;
  cursor: pointer;
  font-size: 15px; /* 设置字体大小为20px */
  position: relative;
  left: 83%;
  top: -45px;
  width: 100px;
  height: 40px;
}
/*表格单元格中的文本内容都将水平居中显示*/
.centered-table .el-table__cell {
  text-align: center;
}
/*表格标题背景变色*/
.centered-table .el-table__header th {
  background-color: #eeeeee; /* 设置标题行的背景色 */
  color: #333; /* 设置标题行的文字颜色 */
}

.customer-list {
  background-color: #ffffff;
  padding: 20px;
}

/*按钮的样式*/
.add-button {
  background-color: #4fc1b0;
  color: #ffffff;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}

.add-button-bottom-right {
  position: absolute;
  bottom: 0;
  top: 110px; /* 将按钮相对于父容器顶部定位 */
  right: 100px;
  margin: 20px; /* 调整按钮与分割线的距离 */
}
.pagination-info {
  margin-bottom: 10px;
  text-align: right; /* 将当前显示条数等信息向右对齐 */
}
/* 调整对话框样式 */
.el-dialog__body {
  padding: 0px 10px 20px 10px; /* 调整内边距 */
}
/* 模态框 */
.qw {
  position: fixed;
  top: 14%;
  left: 10%;
  height: 600px;
  overflow: hidden;
}
.ee {
  border-color: #4fc1b0;
}
.custom-div1 button {
  background-color: #4fc1b0; /* 设置背景颜色为绿色 */
  border: none;
  color: white; /* 设置字体颜色为白色 */
  padding: 10px 20px;
  cursor: pointer;
  font-size: 15px; /* 设置字体大小为20px */
  position: relative;
  left: 85%;
  top: -12px;
  width: 100px;
  height: 40px;
}
.orange-button {
  background-color: var(--orange-color); /* 使用你定义的橙色变量 */
  color: #ffa500; /* 设置文本颜色为白色 */
  font-size: 15px;
  border: none;
  position: relative;
  top: -365px;
}
</style>
